namespace Launcher.Model

import System
import System.IO

import Boo.Lang.Useful.Attributes
import Boo.Lang.Useful.IO as BLUI

callable StartMenuModelEventHandler(model as StartMenuModel)

[singleton]
class StartMenuModel:
"""Description of StartMenuModel"""

	event PreExecution as ApplicationEventHandler
	event PosExecution as ApplicationEventHandler
	event ItemsChanged as StartMenuModelEventHandler
	
	[getter(Applications)]
	_applications = []

	Filter:
		get:
			return _filter
		set:
			_filter = value
			FilterApps()
			ItemsChanged(self)
			
	_filter = ""
	
	_allApps = []
	
	def constructor():
		pass
		
	def Populate():
		_allApps.Clear()
		
		l = GetUserApplications() + GetAllUsersApplications()
		for i as ApplicationInfo in l:
			_allApps.AddUnique(i)
			i.PreExecution += { PreExecution(i) }
			i.RankingChanged += { ItemsChanged(self) }
			i.PosExecution += { PosExecution(i) }

		FilterApps()
		ItemsChanged(self)

	private def FilterApps():
		_allApps = _allApps.Sort()
		_applications = _allApps.Collect({ a as ApplicationInfo | return a.Matches(_filter) })
		
	private def GetUserApplications():
		path = System.Environment.GetFolderPath(Environment.SpecialFolder.Programs)
		return GetApplicationsForPath(path)
		
	private def GetApplicationsForPath(path as string):
		links = [ApplicationInfo(p) for p as string in BLUI.listFiles(path) if p.EndsWith("lnk") and File.Exists(p)]
		return links.Collect({l as ApplicationInfo | return l.IsValid()})

	private def GetAllUsersApplications():
		path = System.Environment.GetFolderPath(Environment.SpecialFolder.Programs)
		path = path.Replace(Environment.UserName, "All Users")
		return GetApplicationsForPath(path)

	def Sort():
		_applications = _applications.Sort()
